package roboticsfmw.core;

public abstract class ManagedComponent implements Runnable {

	private EngineRuntime engine;
	private Thread thread;
	private boolean running;
	private EventBus eventBus;
	private long pollInterval;
	private String name;
	private boolean runnable;
	
	public ManagedComponent(String name, long pollInterval, boolean runnable) throws IllegalArgumentException {
		if (name==null) {
			throw new IllegalArgumentException("Illegal name, must not be null!");		
		}
		this.setName(name);
		if (pollInterval < 0) {
			throw new IllegalArgumentException("Illegal Poll Interval value. Poll intervals must not be < 0!");
		}
		this.pollInterval=pollInterval;
		this.runnable=runnable;
	}
	
	public boolean isRunnable() {
		return this.runnable;
	}
	
	public void setEventBus(EventBus eventBus) {
		this.eventBus = eventBus;
	}
	public EventBus getEventBus() {
		return eventBus;
	}

	protected boolean isRunning() {
		return this.running;
	}
	
	public void turnOn() {
		this.running=true;
	}
	
	public void turnOff() {
		this.running=false;
	}
	
	public void setEngine(EngineRuntime engine) {
		this.engine = engine;
	}

	public EngineRuntime getEngine() {
		return engine;
	}

	public void setThread(Thread thread) {
		this.thread = thread;
	}

	public Thread getThread() {
		return thread;
	}

	public abstract void loop(long i);
	
	public final void run() {
		long i=0;
		while(isRunning()) {
			loop(i++);
			try {
				Thread.sleep(this.pollInterval);
			} catch (InterruptedException e) {
			}
		}
	}

	public long getPollInterval() {
		return pollInterval;
	}

	public void setPollInterval(long pollInterval) {
		this.pollInterval = pollInterval;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
		
}
